from django.core.cache import cache
from django.contrib.auth import get_user_model
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication

from libs.auth.token import get_user_token_key


def authenticate_credentials(request, token):
    user_id = cache.get(get_user_token_key(token))
    if not user_id:
        return None
    user = get_user_model().objects.get(id=user_id)
    return user


def authenticate(request):
    auth = request.META.get('HTTP_AUTHORIZATION', '').split()
    if not auth or auth[0] != 'Token':
        return None

    if len(auth) != 2:
        msg = 'Invalid token header. No credentials provided.'
        raise exceptions.AuthenticationFailed(msg)

    return authenticate_credentials(request, auth[1])


class TokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        user = getattr(request._request, 'user', None)
        if not user:
            return None, None

        auth = getattr(request._request, 'auth', None)
        return user, auth

    def authenticate_header(self, request):
        return 'Token'
